﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Timers;
using Remider.Entity;
using Timer = System.Timers.Timer;

namespace Remider.Utility
{
    class TimerUtility
    {
        private static Timer _scheduleTimer;

        public delegate void AppointOccuredHandler(Appointment appointment);

        public static event AppointOccuredHandler AppointmentOccured;

        public static void Start()
        {
            if (_scheduleTimer == null)
            {
                _scheduleTimer = new Timer(1000);
                _scheduleTimer.Elapsed += new ElapsedEventHandler(ScheduleTimerElapsed);
            }
            _scheduleTimer.Start();

        }

        static void ScheduleTimerElapsed(object sender, ElapsedEventArgs e)
        {
            var now = DateTime.Parse(DateTime.Now.ToString());
            ThreadPool.QueueUserWorkItem(DoJobCheck, now);
        }

        private static void DoJobCheck(object now)
        {
            AppointmentStore.GetLock();
            var needed = AppointmentStore.CurrentAppointments.FindAll(current => current.IsDone != "Y");
            AppointmentStore.ReleaseLock();

            foreach (var appointment in needed)
            {
                if ((DateTime)now == appointment.NextRunDate || (DateTime)now == appointment.LaterRunDate)
                {
                    AppointmentOccured(appointment);
                }

            }
            //Console.WriteLine(now);
        }

        public static void Stop()
        {
            if (_scheduleTimer != null)
            {
                _scheduleTimer.Stop();
                _scheduleTimer.Dispose();
            }
        }

        public static bool Started()
        {
            return _scheduleTimer == null ? false : _scheduleTimer.Enabled;
        }
    }
}